package cn.hairui.fastms.core.controller;


import cn.hairui.fastms.base.cache.CacheManage;
import cn.hairui.fastms.base.config.WebLogInfo;
import cn.hairui.fastms.constant.ConfigConstant;
import cn.hairui.fastms.constant.FieldConstant;
import cn.hairui.fastms.constant.GlobalConstant;
import cn.hairui.fastms.core.annotation.TableResult;
import cn.hairui.fastms.core.bean.SUser;
import cn.hairui.fastms.core.service.*;
import cn.hairui.fastms.util.DateUtil;
import cn.hairui.fastms.util.Md5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author lihairui
 * @since 2020-11-29
 */
@Controller
@RequestMapping("/sUser")
public class SUserController {
    private final static Logger logger = LoggerFactory.getLogger(SUserController.class);
    @Autowired
    private SUserService sUserService;
    @Autowired
    private SUserRoleService sUserRoleService;
    @Autowired
    private SRoleRescService sRoleRescService;
    @Autowired
    private SRescService sRescService;
    @Autowired
    private SUserThemeService sUserThemeService;

    @WebLogInfo(description = "用户提交登录数据")
    @PostMapping("/userLogin")
    public String userLogin(@RequestParam(value = "account", required = true) String account,
                            @RequestParam(value = "password", required = true) String password,
                            HttpServletRequest request, Model model) {

        try {
            String encryptPassword = Md5Util.getMD5ofStr(password);
            //logger.info(encryptPassword);
            //帐号和密码查询
            QueryWrapper<SUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(FieldConstant.USER_PASSWORD[0], encryptPassword)
                    .and(wrapper -> wrapper
                            .eq(FieldConstant.USER_ACCOUNT[0], account).or()
                            .eq(FieldConstant.USER_EMAIL[0], account).or()
                            .eq(FieldConstant.USER_TEL[0], account)
                    );
            SUser sUser = sUserService.getOne(queryWrapper);
            if (sUser == null) {
                model.addAttribute("msg", "您输入的用户名或密码有误");
                model.addAttribute("configMap", CacheManage.configMap);
                return "/login";

            } else {
                request.getSession().setAttribute(GlobalConstant.GLOBAL_SESSION_NAME, sUser);
                //更新登录时间
                sUser.setLastLoginTime(DateUtil.getCurrentDateTimeStr());
                sUserService.saveOrUpdate(sUser);
                return "redirect:/";
            }
        } catch (Exception e) {
            model.addAttribute("msg", "登录失败请重试");
            logger.error("登录失败，错误信息：", e);
        }

        return "redirect:/";
    }

    @WebLogInfo(description = "用户管理列表页面")
    @RequestMapping(value = "/list")
    public String list(HttpServletRequest request) {
        return "pages/core/suser/suser";
    }

    @WebLogInfo(description = "用户管理新增页面")
    @RequestMapping(value = "/add")
    public String add(HttpServletRequest request) {
        return "pages/core/suser/suserAdd";
    }

    @WebLogInfo(description = "用户管理编辑页面")
    @RequestMapping(value = "/edit")
    public String edit(HttpServletRequest request) {
        return "pages/core/suser/suserEdit";
    }

    /*@WebLogInfo(description = "用户管理列表数据获取")
    @RequestMapping(value = "/data")
    @ResponseBody
    public TableResult data(HttpServletRequest request) {
        String pageSizeStr = request.getParameter("rows");
        String pageNumStr = request.getParameter("page");
        Integer pageNum = null;
        int pageSize = GlobalConstant.DEFAULT_PAGE_SIZE;
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSizeStr != null) {
            pageSize = Integer.parseInt(pageSizeStr);
        }
        Page<SUser> page = new Page<>(pageNum, pageSize);


        PageHelper.startPage(pageNum, pageSize);
        List<SUser> sUserList = sUserService.list();
        PageInfo<SUser> pageInfo = new PageInfo<>(sUserList);
        *//*JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", sUserList);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject.toString();*//*
        return new TableResult(pageInfo.getTotal(), sUserList);
    }*/
    @WebLogInfo(description = "用户管理列表数据获取")
    @RequestMapping(value = "/data")
    @ResponseBody
    public TableResult data(HttpServletRequest request) {
        String pageSizeStr = request.getParameter("rows");
        String pageNumStr = request.getParameter("page");
        String userBch = request.getParameter("userBch");
        String userAccount = request.getParameter("userAccount");
        String userName = request.getParameter("userName");

        Integer pageNum = null;
        int pageSize = GlobalConstant.DEFAULT_PAGE_SIZE;
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSizeStr != null) {
            pageSize = Integer.parseInt(pageSizeStr);
        }

        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<SUser> queryWrapper = new QueryWrapper<>();
        if (userBch != null && !"".equals(userBch)) {
            queryWrapper.eq(FieldConstant.USER_BCH[0], userBch);
        }
        if (userAccount != null && !"".equals(userAccount)) {
            queryWrapper.eq(FieldConstant.USER_ACCOUNT[0], userAccount);
        }
        if (userName != null && !"".equals(userName)) {
            queryWrapper.eq(FieldConstant.USER_NAME[0], userName);
        }
        List<SUser> sUserList = sUserService.list(queryWrapper);
        PageInfo<SUser> pageInfo = new PageInfo<>(sUserList);
        /*JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", sDicList);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject.toString();*/

        return new TableResult(pageInfo.getTotal(), sUserList);

    }

    @WebLogInfo(description = "用户管理详细数据获取")
    @RequestMapping(value = "/detail")
    @ResponseBody
    public JSONObject data(HttpServletRequest request, String id) {
        QueryWrapper<SUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.ID[0], id);
        SUser sUser = sUserService.getOne(queryWrapper);
        JSONObject json = JSONObject.fromObject(sUser);
        return json;
    }

    @WebLogInfo(description = "用户管理数据保存")
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save(HttpServletRequest request, SUser sUser, String flag) {
        SUser currentUser = (SUser) request.getSession().getAttribute(GlobalConstant.GLOBAL_SESSION_NAME);
        if (GlobalConstant.OPERATION_ADD.equals(flag)) {
            //新增保存
            sUser.setUserPassword(Md5Util.getMD5ofStr(CacheManage.configMap.get(ConfigConstant.CFG_SYSTEM_DEFAULT_PASSWORD)));
            //判断是否已经存在
            QueryWrapper<SUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(FieldConstant.USER_ACCOUNT[0], sUser.getUserAccount());

            if (sUserService.list(queryWrapper).size() > 0) {
                //已存在 不允许新增
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0003).toJSONString();
            } else {
                //不存在 允许新增
                sUser.setCreateTime(DateUtil.getCurrentDateTimeStr());
                sUser.setCreateUser(currentUser.getUserAccount());
                sUser.setUpdateTime(DateUtil.getCurrentDateTimeStr());
                sUser.setUpdateUser(currentUser.getUserAccount());
                sUserService.save(sUser);
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
            }

        } else if (GlobalConstant.OPERATION_EDIT.equals(flag)) {
            //更新保存
            sUser.setUpdateTime(DateUtil.getCurrentDateTimeStr());
            sUser.setUpdateUser(currentUser.getUserAccount());
            boolean result = sUserService.saveOrUpdate(sUser);
            if (result) {
                //更新成功
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
            } else {
                //更新失败
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0001).toJSONString();
            }
        } else {
            return null;
        }
    }

    @WebLogInfo(description = "用户管理数据删除")
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Transactional
    public String delete(HttpServletRequest request, String[] id) {

        List<String> idList = Arrays.asList(id);
        //删除用户对应的角色
        sUserRoleService.removeByUserAccounts(idList);
        //删除用户对应的主题
        sUserThemeService.removeByUserAccounts(idList);

        QueryWrapper<SUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(FieldConstant.ID[0], id);
        sUserService.remove(queryWrapper);
        return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
    }

    @WebLogInfo(description = "用户管理修改状态")
    @PostMapping(value = "/changests")
    @ResponseBody
    @Transactional
    public String changests(HttpServletRequest request, String[] id, String status) {

        for (int i = 0; i < id.length; i++) {
            UpdateWrapper<SUser> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(FieldConstant.ID[0], id[i]).set(FieldConstant.USER_STS[0], status);
            sUserService.update(null, updateWrapper);
        }
        return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
    }

    @WebLogInfo(description = "用户管理重置密码")
    @PostMapping(value = "/resetpwd")
    @ResponseBody
    @Transactional
    public String resetpwd(HttpServletRequest request, String[] id) {
        for (int i = 0; i < id.length; i++) {
            String password = Md5Util.getMD5ofStr(CacheManage.configMap.get(ConfigConstant.CFG_SYSTEM_DEFAULT_PASSWORD));
            UpdateWrapper<SUser> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(FieldConstant.ID[0], id[i]).set(FieldConstant.USER_PASSWORD[0], password);
            sUserService.update(null, updateWrapper);
        }
        return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
    }


    @WebLogInfo(description = "修改密码")
    @RequestMapping(value = "/modifyPassword")
    public String modifyPassword(HttpServletRequest request, Model model) {
        SUser sUser = (SUser) request.getSession().getAttribute(GlobalConstant.GLOBAL_SESSION_NAME);
        if (sUser != null) {
            model.addAttribute("userAccount", sUser.getUserAccount());
            return "pages/core/suser/modifyPassword";
        } else {
            return "redirect:/login";
        }
    }

    @WebLogInfo(description = "个人信息")
    @RequestMapping(value = "/personalInfo")
    public String personalInfo(HttpServletRequest request, Model model) {
        SUser sUser = (SUser) request.getSession().getAttribute(GlobalConstant.GLOBAL_SESSION_NAME);
        if (sUser != null) {
            model.addAttribute("user", sUser);
            return "pages/core/suser/personalInfo";
        } else {
            return "redirect:/login";
        }
    }

    @WebLogInfo(description = "修改用户密码")
    @PostMapping(value = "/updateModifyPassword")
    @ResponseBody
    @Transactional
    public String updateModifyPassword(HttpServletRequest request) {
        String userAccount = request.getParameter("userAccount");
        String originalPassword = request.getParameter("originalPassword");
        String password = request.getParameter("password");

        String originalPasswordEncrypt = Md5Util.getMD5ofStr(originalPassword);

        QueryWrapper<SUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.USER_ACCOUNT[0], userAccount);

        SUser sUser = sUserService.getOne(queryWrapper);
        if (sUser != null) {
            String passwordEncrypt = sUser.getUserPassword();
            if (passwordEncrypt.equals(originalPasswordEncrypt)) {
                sUser.setUserPassword(Md5Util.getMD5ofStr(password));
                sUser.setPassModiDt(DateUtil.getCurrentDateTimeStr());
                sUserService.saveOrUpdate(sUser);
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
            } else {
                //原密码不正确
                return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0006).toJSONString();
            }
        } else {
            return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0005).toJSONString();
        }
    }
}

